import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {routerRedux} from 'dva/router';
import { remote } from '../../services/api';
import {
  ChartCard,
  yuan,
  MiniArea,
  MiniBar,
  MiniProgress,
  Field,
  Bar,
  Pie,
  TimelineChart,
} from 'components/Charts';
import Trend from 'components/Trend';

import moment from 'moment';
import { Row,Progress, Col,Tooltip,Radio, Card, Form, Input, Select, Icon, Button, Dropdown, Menu, InputNumber, DatePicker, Modal, message, Badge, Divider,Table } from 'antd';
import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
const { TextArea } = Input;

import styles from './TableList.less';

const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj => Object.keys(obj).map(key => obj[key]).join(',');
const statusMap = ['default', 'processing', 'success', 'error'];
const status = ['关闭', '运行中', '已上线', '异常'];

const CreateForm = Form.create()((props) => {
  const { modalVisible, form, handleAdd, handleModalVisible } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      if(fieldsValue.content_tag.length == 0){
        fieldsValue.content = JSON.stringify(fieldsValue.content.split('\n'))
      }else{
        var tags = fieldsValue.content_tag.split('\n')
        var contents = fieldsValue.content.split('\n')
        var newContents = []
        for(var i = 0;i < contents.length;i++){
          for(var j = 0;j < tags.length;j++){
            newContents.push(contents[i]+'+'+tags[j])
          }
        }
        fieldsValue.content = JSON.stringify(newContents)
      }
    
      handleAdd(fieldsValue);
    });
  };

  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 7 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 12 },
      md: { span: 10 },
    },
  };

  return (
    <Modal
      title="新建任务"
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
    >
      <FormItem
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 15 }}
        label="名称"
      >
        {form.getFieldDecorator('name', {
          rules: [{ required: true, message: '请输入名称' }],
        })(
          <Input placeholder="请输入" />
        )}
      </FormItem>
      <FormItem
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 15 }}
        label="域名"
      >
        {form.getFieldDecorator('content', {
          rules: [{ required: true, message: '请输入域名' }],
        })(
          <TextArea style={{ minHeight: 32 }} placeholder="请输入域名" rows={3} />
        )}
      </FormItem>
      <FormItem
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 15 }}
        label="域名特征值"
      >
        {form.getFieldDecorator('content_tag', {
          rules: [{ required: false, message: '请输入域名特征值' }],
        })(
          <TextArea style={{ minHeight: 32 }} placeholder="请输入域名特征值" rows={3} />
        )}
      </FormItem>
      <FormItem
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 15 }}
        label="执行时间"
      >
        {form.getFieldDecorator('times', {
          rules: [{ required: true, message: '请输入执行时间' }],
        })(
          <Input placeholder="请输入" />
        )}
      </FormItem>
      <FormItem
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 15 }}
        label="每日次数"
      >
        {form.getFieldDecorator('retry', {
          rules: [{ required: true, message: '请输入每日次数' }],
        })(
          <Input placeholder="请输入" />
        )}
      </FormItem>
      <FormItem
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 15 }}
        label="优先级"
      >
        {form.getFieldDecorator('priority', {
          rules: [{ required: true, message: '请输入优先级' }],
        })(
          <Input placeholder="请输入" />
        )}
      </FormItem>
      <FormItem
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 15 }}             
            label="是否点击"
            >
              <div>
                {form.getFieldDecorator('is_click', {
                  initialValue: false,
                  rules: [{ required: true, message: '请选择是否点击' }],
                })(
                  <Radio.Group>
                    <Radio value={true}>是</Radio>
                    <Radio value={false}>否</Radio>
                  </Radio.Group>
                )}
              </div>
      </FormItem>
      <FormItem
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 15 }}
        label="MaxGroup"
      >
        {form.getFieldDecorator('click_max_group', {
          rules: [{ required: true, message: '请输入ClickMaxGroup' }],
        })(
          <Input placeholder="请输入" />
        )}
      </FormItem>
    </Modal>
  );
});

@connect(({ rule, loading }) => ({
  rule,
  loading: loading.models.rule,
}))
@Form.create()
export default class TableList extends PureComponent {
  state = {
    modalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'rule/fetch',
      payload: {
        page:1,
        size:10
      },

    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      page: pagination.current,
      size: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'rule/fetch',
      payload: params,
    });
  }

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'rule/fetch',
      payload: {},
    });
  }

  refresh = () => {
    const { form, dispatch } = this.props;
    dispatch({
      type: 'rule/fetch',
      payload: {
        page:1,
        size:10
      },
    });
  }

  toggleForm = () => {
    this.setState({
      expandForm: !this.state.expandForm,
    });
  }

  handleMenuClick = (e) => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;

    if (!selectedRows) return;

    switch (e.key) {
      case 'remove':
        dispatch({
          type: 'rule/remove',
          payload: {
            no: selectedRows.map(row => row.no).join(','),
          },
          callback: () => {
            this.setState({
              selectedRows: [],
            });
          },
        });
        break;
      default:
        break;
    }
  }

  handleSelectRows = (rows) => {
    this.setState({
      selectedRows: rows,
    });
  }

  handleModalVisible = (flag) => {
    this.setState({
      modalVisible: !!flag,
    });
  }

  handleAdd = (fields) => {
    fields.content_tag
    this.props.dispatch({
      type: 'rule/add',
      payload: {
        click_max_group: parseInt(fields.click_max_group),
        content:fields.content,
        is_click:fields.is_click,
        name:fields.name,
        priority:parseInt(fields.priority),
        times:fields.times,
        retry:parseInt(fields.retry)
      },
    })

    message.success('添加成功');
      this.setState({
      modalVisible: false,
    });
  }

  renderCard(card1,card2){
    var cacu = function (record) {
      if (record.total_count == 0) {
        return 0
      }
      return parseInt(record.done_count / record.total_count * 100)
    }

    const topColResponsiveProps = {
      xs: 24,
      sm: 12,
      md: 12,
      lg: 12,
      xl: 12,
      style: { marginBottom: 24 },
    };
    var cardp1 = cacu(card1)+'%'
    var cardp2 = cacu(card2)+'%'
    return (
      <Fragment>
        <Row gutter={24}>  
        <Col {...topColResponsiveProps}>
            <ChartCard
              bordered={false}
              title="域名任务"
              totalLeft={card1.name}
              totalRight={cardp1}
              footer={
                <div style={{ whiteSpace: 'nowrap', overflow: 'hidden' }}>
                 <Trend  style={{ marginRight: 16 }}>
                    任务ID<span className={styles.trendText}>{card1.task_id}</span>
                  </Trend>
                  <Trend  style={{ marginRight: 16 }}>
                    已完成<span className={styles.trendText}>{card1.done_count}</span>
                  </Trend>
                  <Trend >
                    全部<span className={styles.trendText}>{card1.total_count}</span>
                  </Trend>
                </div>
              }
              contentHeight={46}
            >
              <MiniProgress percent={cacu(card1)} strokeWidth={8} target={100} color="#13C2C2" />
            </ChartCard>
          </Col>
          <Col {...topColResponsiveProps}>
            <ChartCard
              bordered={false}
              title="点击任务"
              totalLeft={card2.name}
              totalRight={cardp2}
               footer={
                <div style={{ whiteSpace: 'nowrap', overflow: 'hidden' }}>
                 <Trend  style={{ marginRight: 16 }}>
                    任务ID<span className={styles.trendText}>{card2.task_id}</span>
                  </Trend>
                  <Trend  style={{ marginRight: 16 }}>
                    已完成<span className={styles.trendText}>{card2.done_count}</span>
                  </Trend>
                  <Trend >
                    全部<span className={styles.trendText}>{card2.total_count}</span>
                  </Trend>
                </div>
              }
              contentHeight={46}
            >
              <MiniProgress percent={cacu(card2)} strokeWidth={8} target={80} color="#13C2C2" />
            </ChartCard>
          </Col>
        </Row>
      </Fragment>
    )
  }

  renderExpand(){

    const columns = [
      { title: 'ID', dataIndex: 'id', key: 'id' },
      { title: '类型', dataIndex: 'work_type', key: 'work_type' },
      { title: '进度',
      key: 'state',
      render: 
      () =>  (
        <div style={{ width: 170 }}>
          <Progress percent={60} size="small" status="active"/>
        </div>)
      },
 
      { title: '更新时间', dataIndex: 'date', key: 'date' },
      { title: '创建时间', dataIndex: 'date', key: 'date' },

      {
        title: '操作',
        dataIndex: 'operation',
        key: 'operation',
        render: 
        () => (
          <Fragment>
            <a href="">查看</a>
            <Divider type="vertical" />
            <a href="">下载</a>
          </Fragment>
        ),
      },
    ];

    const data = [];
    for (let i = 0; i < 3; ++i) {
      data.push({
        key: i,
        date: '2014-12-24 23:12:00',
        id: i+1,
        work_type: '域名',
      });
    }
    return (
      <Table
        showHeader={true}
        columns={columns}
        dataSource={data}
        pagination={false}
      />
    );
  }
  onRow = (record) =>{
    const { dispatch } = this.props;
    return {
      onClick: () => {
        dispatch(routerRedux.push('/profile/advanced?task_id='+record.id));
        return
      },
    };
  }
  openDetail = (record) =>{
    console.log('openDetail')
    const { dispatch } = this.props;
    dispatch(routerRedux.push('/profile/advanced?task_id='+record.id));
    return
  }

  delete = (record) =>{
    console.log('delete')
    this.props.dispatch({
      type: 'rule/delete',
      payload: {
        id : record.id,
      }
    })
  }

  taskDo = (record) =>{
    this.props.dispatch({
      type: 'rule/taskdo',
      payload: {
        task_id : record.id,
      }
    })
  }

  openInNewTab = (task) =>{
    console.log(remote)
    var url = remote + `/api/task/urls?task_id=`+task.id
    var win = window.open(url, '_blank');
    win.focus();  
  }

  render() {
    const columns = [
      {
        title: 'ID',
        dataIndex: 'id',
      },
      {
        title: '名称',
        dataIndex: 'name',
      },
      {
        title: '优先级',
        dataIndex: 'priority',
      },
      {
        title: '状态',
        dataIndex: 'is_running',
        filters: [
          {
            text: status[0],
            value: false,
          },
          {
            text: status[1],
            value: true,
          }
        ],
        render(val) {
          return <Badge status={statusMap[val?0:1]} text={status[val?0:1]} />;
        },
      },
      {
        title: '创建时间',
        dataIndex: 'create_time',
        sorter: true,
        render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
      },
      {
        title: '操作',  
        render: (val , record) => (
          <span>
            <a onClick={()=> this.openDetail(record)}>详情</a>  
            <Divider type="vertical" />
            <a onClick={()=> this.openInNewTab(record)}>真实地址 </a>
            <Divider type="vertical" />
            <a onClick={()=> this.taskDo(record)}>执行</a>  
            {/* <Divider type="vertical" />
            <a onClick={()=> this.delete(record)}>删除 </a> */}
          </span>
        ),
      },
    ];

    const { rule: { data,domainR,clickR }, loading } = this.props;
    const { selectedRows, modalVisible } = this.state;

    const menu = (
      <Menu onClick={this.handleMenuClick} selectedKeys={[]}>
        <Menu.Item key="remove">删除</Menu.Item>
        <Menu.Item key="approval">批量审批</Menu.Item>
      </Menu>
    );

    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
    };

    return (
      <PageHeaderLayout title="任务列表">
        {this.renderCard(domainR,clickR)}
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListOperator}>
              <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
                新建
              </Button>
              {
                selectedRows.length > 0 && (
                  <span>
                    <Button>批量操作</Button>
                    <Dropdown overlay={menu}>
                      <Button>
                        更多操作 <Icon type="down" />
                      </Button>
                    </Dropdown>
                  </span>
                )
              }
            </div>
            <StandardTable
              loading={loading}
              data={data}
              columns={columns}
              onRow={this.onRow}
              // onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <CreateForm
          {...parentMethods}
          modalVisible={modalVisible}
        />
      </PageHeaderLayout>
    );
  }
}
